#include "sqlitedb.h"
#include <QDebug>

SqliteDB::SqliteDB(QObject *parent) : QObject(parent)
{

}

//连接数据库
bool SqliteDB::connectDB()
{
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName("control.db");
    if(!database.open())
    {
        qDebug()<< "connect to control.db failed!";
        return false;
    }
    else
    {
        query = new QSqlQuery(database);
        qDebug() << "connect to control.db successfully!";
        return true;
    }
}

//关闭数据库
void SqliteDB::closeDB()
{
    database.close();
}

//查询数据库
QStringList SqliteDB::getDBData(const QString sql)
{
    //QStringList strList;
    strlist.clear();
    query->prepare(sql);
    if(!query->exec())
    {
        qDebug() <<sql+"    exec failed !";
    }
    else
    {
        while(query->next())
        {
            strlist << query->value(0).toString();
        }

        qDebug() << "strList的长度是: "+strlist.length();
    }

    query->clear();
    return strlist;
}

//查询数据库
QStringList SqliteDB::getDBData(int n, QString sql){
    //QStringList strList;
    query->prepare(sql);
    if(!query->exec())
    {
        qDebug() << sql + "     exec failed !";
    }
    else
    {
        while (query->next()) {
            for(int i=0; i<n; i++){
                strlist << query->value(i).toString();
            }
        }

        qDebug() << "strList的长度是："+strlist.length();
    }
    return strlist;
}

QStringList SqliteDB::strList() const
{
    return strlist;
}

QSqlQuery * SqliteDB::m_query() const
{
    return query;
}

QString SqliteDB::getData(int i){
    return strlist.at(i);
}

QString SqliteDB::getAData(QString sql)
{
    query->prepare(sql);
    if(!query->exec())
    {
        qDebug() << sql + "     exec failed !";
    }
    else
    {
        query->next();
        QString tmp = query->value(0).toString();
        return query->value(0).toString();

    }
    return "";
}

int SqliteDB::strCount()
{
    return strlist.length();
}
